//###############
//FILE : DirAllFilesCommand.java
//WRITER : Daniel Lowengrub, daniel_i_l, 320687098
//EXERCISE : oop ex3 2011
//DESCRIPTION:
//See below
//###############
package oop.ex3.filemanager;

import java.util.ArrayList;
import java.util.TreeSet;

import oop.ex3.communication.SocketAddress;
import oop.ex3.protocol.sessions.FileWantAllFilesSession;

/**
 * Implements the DIRALLFILES command as specified in the assignment.
 * @author daniel
 */
public class DirAllFilesCommand extends UserCommand{
    private static final String DIR_ALL_COMMAND = "DIRALLFILES";
    private TreeSet<String> _retreivedFiles;
    private NameServerDatabase _nameServers;
    private NameServerConnection _nameConnection;

    /**
     * Construct a dirallfiles command.
     * @param connection The connection this command uses to talk to a NS.
     */
    public DirAllFilesCommand(NameServerConnection connection) {
        super (DIR_ALL_COMMAND);
        _retreivedFiles = new TreeSet<String>();
        _nameConnection = connection;
        _nameServers = connection.getNameServerDatabase();
    }


    @Override
    public boolean executeCommand(String command) {

        //first retreive all the addresses we need
        _retreivedFiles.clear();
        _nameServers.initServerSearch();
        ArrayList<SocketAddress> activeSet = _nameServers.getActiveSet();

        while (activeSet.size() != 0) {
            for (SocketAddress address : activeSet)
                appendFilesFromServer(address);

            _nameServers.updateActiveSet(_nameConnection);
            activeSet = _nameServers.getActiveSet();
        }

        //now print the files
        for (String fileName : _retreivedFiles)
            System.out.println(fileName);

        return true;

    }

    //get all the files from a specific NS.
    private void appendFilesFromServer(SocketAddress nameServer) {
        //System.out.println("getting files from: " + nameServer.getIp() + " : " + nameServer.getPort());
        if (!_nameConnection.initializeStreams(nameServer))
            return;

        FileWantAllFilesSession wantAllFiles = new FileWantAllFilesSession();
        _nameConnection.initializeSession(wantAllFiles);
        if (wantAllFiles.executeSession(_nameConnection.getInputStream(),
                _nameConnection.getOutputStream())) {
            _retreivedFiles.addAll(wantAllFiles.getFileNames());
        }

        _nameConnection.closeConnection();
    }
}
